<template>
  <div class="config-page">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <input
        v-model="searchKeyword"
        class="form-control"
        placeholder="搜索配置名称/关键词"
        @keyup.enter="handleSearch"
      />
      <button @click="handleSearch" class="btn btn-secondary">
        <i class="fa fa-search mr-1"></i>搜索
      </button>
      <button @click="clearSearch" class="btn btn-outline-secondary">
        <i class="fa fa-refresh mr-1"></i>清空
      </button>
      <button @click="openCreateConfigDialog" class="btn btn-primary">
        <i class="fa fa-plus mr-1"></i> 新增
      </button>
    </div>

    <!-- 配置表格 -->
    <div class="table-container">
      <el-table
        :data="configPage.list"
        border
        stripe
        :row-class-name="rowClassNameHandler"
        style="width: 100%"
      >
        <el-table-column label="条件名称" prop="name" width="190"/>
        <el-table-column label="异常阀值" prop="keywords"/>
        <el-table-column label="操作" width="300" align="center">
          <template #default="scope">
            <button @click.stop="handleEditConfig(scope.row)" class="btn btn-sm btn-primary">
              <i class="fa fa-edit mr-1"></i>编辑
            </button>
            <button @click.stop="handleDeleteConfig(scope.row.id)" class="btn btn-sm btn-danger">
              <i class="fa fa-trash mr-1"></i>删除
            </button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handlePageSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageParam.pageNo"
        :page-sizes="[10, 20, 50]"
        :page-size="pageParam.pageSize"
        :total="configPage.total"
        layout="total, sizes, prev, pager, next, jumper"
      />
    </div>

    <!-- 新增/编辑配置弹窗 -->
    <el-dialog
      v-model="showConfigDialog"
      :title="isEditConfig ? '编辑词组' : '新建词组'"
      width="500px"
      :close-on-click-modal="false"
      ref="configDialogRef"
    >
      <div class="form-group">
        <label>条件名称 <span class="required">*</span>:</label>
        <input
          v-model="configForm.name"
          class="form-control"
          required
          placeholder="请输入关键词组名称"
        />
      </div>

      <div class="form-group">
        <label>阀值 <span class="required">*</span>:</label>
        <textarea
          v-model="configForm.keywords"
          class="form-control"
          required
          placeholder="请输入关键词组列表，多个关键词用逗号分隔"
          rows="=8"
        ></textarea>
      </div>

      <template #footer>
        <button @click="showConfigDialog = false" class="btn btn-secondary mr-5">
          <i class="fa fa-times mr-1"></i>取消
        </button>
        <button @click="submitConfigForm" class="btn btn-primary">
          <i class="fa fa-check mr-1"></i>提交
        </button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, toRefs } from 'vue';
import { MapConfigApi } from '@/api/member/map/mapConfigApi';

defineOptions({ name: 'TraceExceptionConfig' })

// 类型定义
interface MapConfig {
  id: string;
  name: string;
  keywords: string;
  warnType: number
}

// 响应式状态
const state = reactive({
  configPage: { list: [] as MapConfig[], total: 0 },
  pageParam: { pageNo: 1, pageSize: 10 },
  searchKeyword: '',
  showConfigDialog: false,
  isEditConfig: false,
  configForm: {
    id: '',
    name: '',
    keywords: '',
    warnType: 7
  },
  message: ''
});

const {
  configPage,
  pageParam,
  searchKeyword,
  showConfigDialog,
  isEditConfig,
  configForm,
  message
} = toRefs(state);

// 弹窗引用
const configDialogRef = ref<HTMLElement | null>(null);
const selectedConfigId = ref('');

// 消息提示
const setMessage = (text: string, duration = 3000) => {
  message.value = text;
  duration && setTimeout(() => message.value = '', duration);
};

// 获取配置列表
const getConfigPage = async () => {
  try {
    const params = {
      pageNo: pageParam.value.pageNo,
      pageSize: pageParam.value.pageSize,
      keyword: searchKeyword.value,
      warnType: 7
    };

    const res = await MapConfigApi.getMapConfigPage(params);
    if (res) {
      configPage.value.list = res.list || [];
      configPage.value.total = res.total || 0;
    }
  } catch (error) {
    setMessage('获取配置列表失败', 3000);
    console.error(error);
  }
};

// 搜索配置
const handleSearch = () => {
  pageParam.value.pageNo = 1;
  getConfigPage();
};

// 清空搜索条件
const clearSearch = () => {
  searchKeyword.value = '';
  handleSearch();
};

// 表格行样式
const rowClassNameHandler = ({ row }: { row: MapConfig }) => {
  return row.id === selectedConfigId.value ? 'selected-config' : '';
};

// 打开新增配置弹窗
const openCreateConfigDialog = () => {
  isEditConfig.value = false;
  configForm.value = {
    id: '',
    name: '',
    keywords: '',
    warnType: 7
  };
  showConfigDialog.value = true;
};

// 编辑配置
const handleEditConfig = (row: MapConfig) => {
  isEditConfig.value = true;
  configForm.value = { ...row };
  showConfigDialog.value = true;
  selectedConfigId.value = row.id;
};

// 删除配置
const handleDeleteConfig = async (id: string) => {
  if (confirm('确定要删除该配置吗？')) {
    try {
      await MapConfigApi.deleteMapConfig(id);
      setMessage('配置已删除', 3000);
      getConfigPage();
      if (id === selectedConfigId.value) {
        selectedConfigId.value = '';
      }
    } catch (error) {
      setMessage('删除配置失败', 3000);
      console.error(error);
    }
  }
};

// 提交配置表单
const submitConfigForm = async () => {
  if (!configForm.value.name) {
    setMessage('请填写词组名称', 3000);
    return;
  }
  if (!configForm.value.keywords) {
    setMessage('请填写关键词列表', 3000);
    return;
  }

  try {
    if (isEditConfig.value) {
      await MapConfigApi.updateInOutHzConfig(configForm.value);
      setMessage('配置已更新', 3000);
    } else {
      await MapConfigApi.createInOutHzConfig(configForm.value);
      setMessage('配置已创建', 3000);
    }

    showConfigDialog.value = false;
    await getConfigPage();
  } catch (error) {
    setMessage(isEditConfig.value ? '更新配置失败' : '创建配置失败', 3000);
    console.error(error);
  }
};

// 分页大小变更
const handlePageSizeChange = (size: number) => {
  pageParam.value.pageSize = size;
  pageParam.value.pageNo = 1;
  getConfigPage();
};

// 当前页变更
const handleCurrentChange = (page: number) => {
  pageParam.value.pageNo = page;
  getConfigPage();
};

// 生命周期 - 挂载时
onMounted(() => {
  getConfigPage();
});
</script>

<style scoped>
.config-page {
  padding: 20px;
  //max-width: 1400px;
  margin: 0 auto;
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  max-width: 500px;
}

.search-bar .form-control {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.table-container {
  background-color: white;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  margin-bottom: 15px;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

.form-group {
  margin-bottom: 12px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

.required {
  color: #f44336;
}

.form-control {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

.btn {
  padding: 8px 16px;
  border-radius: 4px;
  border: none;
  cursor: pointer;
  font-size: 14px;
  display: inline-flex;
  align-items: center;
}

.btn-primary {
  background-color: #42b983;
  color: white;
}

.btn-primary:hover {
  background-color: #359e75;
}

.btn-secondary {
  background-color: #e5e7eb;
  color: #374151;
}

.btn-secondary:hover {
  background-color: #d1d5db;
}

.btn-danger {
  background-color: #f44336;
  color: white;
}

.btn-danger:hover {
  background-color: #d32f2f;
}

.btn-outline-secondary {
  background-color: transparent;
  border: 1px solid #e5e7eb;
  color: #374151;
}

.btn-outline-secondary:hover {
  background-color: #f5f5f5;
}

.btn-sm {
  padding: 4px 8px;
  font-size: 12px;
  margin-right: 5px;
}

.mr-1 {
  margin-right: 5px;
}

.mr-5 {
  margin-right: 15px;
}

.selected-config {
  background-color: #e6f7ee;
}
</style>
